import {rule as form} from "../config/index.js";
import api from "../config/api.js";

export default {
    template: `
          <el-dialog
            v-model="visible"
            title="规则配置"
            width="80%">
                <el-form  :model="formData" :rules="formRules" ref="formRef" label-width="120px">
                    <el-form-item label="url">
                        <el-input disabled v-model="formData.url" placeholder="请输入url" ></el-input>
                    </el-form-item>
                    <el-row justify="space-between">
                        <el-col :span="12">
                            <el-form-item label="参数规则:" prop="rule">
                                <jsInput ref="inputRef" v-if="visible" v-model:value="formData.rule" style="height: 60vh" ></jsInput>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="参数格式:" prop="paramType">
                                <jsInput  v-if="visible" v-model:value="formData.paramType" style="height: 60vh"  ></jsInput>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="visible=false">取消</el-button>
                <el-button type="primary" @click="operation.save">保存</el-button>
              </span>
            </template>
        </el-dialog>
    `, setup(props, context) {
        const formRef = Vue.ref(null);
        const visible = Vue.ref(false)
        const inputRef = Vue.ref(null)
        const res = Vue.ref({})
        const resTime = Vue.ref(0)
        const operation = {
            save: async () => {
                (await getRef(formRef)).validate(async (valid) => {
                    if (valid) {
                        context.emit("save", {id: form.formData.id, rule: form.formData.rule})
                    }
                })
            },

        }
        Vue.watch(visible, async val => {
            if (val) {
                const {rule} = await api.getRule({id: form.formData.id})
                form.formData.rule = rule;
                (await getRef(inputRef)).setValue(rule)
            }
            val || (await getRef(formRef)).resetFields()
            form.formatJson('rule', form.formData.rule)
            form.formatJson('paramType', form.formData.paramType)
            form.formData.token = Vue.ref(localStorage.getItem('token'))
        })
        return Object.assign({
            visible, formRef, operation, res, resTime, inputRef
        }, form)
    }, components: {
        jsInput: (await import('/component/js_input/js/index.js')).default,
    }
}